<template>
  <view class="checkin-page">
 
    <!-- 日历卡片 -->
    <view class="calendar-card">
      <view class="calendar-header">
        <text class="month">{{ currentMonth }}</text>
        <text class="year">{{ currentYear }}</text>
      </view>
      <view class="day-container">
        <text class="day">{{ currentDay }}</text>
        <text class="weekday">{{ currentWeekday }}</text>
      </view>
      <view class="calendar-footer">
        <text class="lunar-date">{{ lunarDate }}</text>
      </view>
    </view>

    <!-- 打卡信息 -->
    <view class="checkin-info">
      <view class="info-item">
        <text class="info-icon bi bi-award"></text>
        <view class="info-content">
          <text class="info-title">奖励积分</text>
          <text class="info-value">50分</text>
        </view>
      </view>
      <view class="info-item">
        <text class="info-icon bi bi-calendar-check"></text>
        <view class="info-content">
          <text class="info-title">本月打卡</text>
          <text class="info-value">{{ checkinDays }} 天</text>
        </view>
      </view>
      <view class="info-item">
        <text class="info-icon bi bi-star"></text>
        <view class="info-content">
          <text class="info-title">当前积分</text>
          <text class="info-value">{{ currentScore }}分</text>
        </view>
      </view>
    </view>

    <!-- 打卡按钮 -->
    <view class="checkin-btn-container">
      <view 
        :class="['checkin-btn', isCheckedIn ? 'checked' : '']"
        @tap="handleCheckin"
      >
        <text v-if="!isCheckedIn">立即打卡</text>
        <text class="uni-my-4" v-else>今日已打卡</text>
        <view v-if="isCheckedIn" class="checked-mark">

        </view>
      </view>
      <text class="checkin-tip">每日打卡即可获得积分奖励，连续打卡奖励更多！</text>
    </view>

    <!-- 打卡日历 -->
    <view class="mini-calendar">
      <view class="calendar-title">
        <text class="bi bi-calendar3"></text>
        <text>本月打卡记录</text>
      </view>
      <view class="week-header">
        <text v-for="(day, index) in weekDays" :key="index" class="week-item">{{ day }}</text>
      </view>
      <view class="days-grid">
        <view 
          v-for="(day, index) in calendarDays" 
          :key="index" 
          :class="['day-item', day.isToday ? 'today' : '', day.isChecked ? 'checked' : '', !day.inMonth ? 'other-month' : '']"
        >
          <text>{{ day.day }}</text>
          <view v-if="day.isChecked" class="checked-dot"></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useUserStore } from '@/stores/userStore';

// 获取用户存储
const userStore = useUserStore();

// 今日日期相关数据
const now = new Date();
const currentYear = ref(now.getFullYear());
const currentMonth = ref(now.toLocaleString('zh-CN', { month: 'long' }));
const currentDay = ref(now.getDate());
const currentWeekday = ref(now.toLocaleString('zh-CN', { weekday: 'long' }));
const lunarDate = ref('辛丑年正月初一'); // 简化处理，实际项目中可以使用农历转换库
const isCheckedIn = ref(false);
const checkinDays = ref(0);
const currentScore = ref(userStore.userInfo?.score || 0);

// 星期头部
const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

// 本月打卡记录 (示例数据)
const checkedDates = ref([5, 10, 15, 20, 25]);

// 日历数据
const calendarDays = ref([]);

// 计算并更新日历数据
const updateCalendarDays = () => {
  const year = currentYear.value;
  const month = now.getMonth();
  
  // 获取当月第一天
  const firstDay = new Date(year, month, 1);
  // 获取当月最后一天
  const lastDay = new Date(year, month + 1, 0);
  // 当月天数
  const daysInMonth = lastDay.getDate();
  // 第一天是星期几
  const firstDayWeek = firstDay.getDay();
  
  // 创建日历网格（6行7列）
  const days = [];
  
  // 添加上月的日期
  const prevMonthLastDay = new Date(year, month, 0).getDate();
  for (let i = 0; i < firstDayWeek; i++) {
    days.push({
      day: prevMonthLastDay - firstDayWeek + i + 1,
      inMonth: false,
      isToday: false,
      isChecked: false
    });
  }
  
  // 添加当月的日期
  for (let i = 1; i <= daysInMonth; i++) {
    days.push({
      day: i,
      inMonth: true,
      isToday: i === currentDay.value,
      isChecked: checkedDates.value.includes(i)
    });
  }
  
  // 添加下月的日期以填满网格
  const remainingDays = 42 - days.length;
  for (let i = 1; i <= remainingDays; i++) {
    days.push({
      day: i,
      inMonth: false,
      isToday: false,
      isChecked: false
    });
  }
  
  calendarDays.value = days;
};

// 检查用户是否已打卡
const checkUserCheckinStatus = () => {
  const lastCheckinDate = uni.getStorageSync('lastCheckinDate');
  const today = new Date().toDateString();
  
  // 如果上次打卡日期是今天，则已打卡
  isCheckedIn.value = lastCheckinDate === today;
  
  console.log('打卡状态检查:', isCheckedIn.value ? '今日已打卡' : '今日未打卡');
};

// 获取本月打卡次数
const getMonthlyCheckins = () => {
  const checkinHistory = uni.getStorageSync('checkinHistory') || {};
  const yearMonth = `${currentYear.value}-${now.getMonth()+1}`;
  
  checkinDays.value = (checkinHistory[yearMonth] || []).length;
};

// 处理打卡逻辑
const handleCheckin = async () => {
  if (isCheckedIn.value) {
    uni.showToast({
      title: '今日已打卡',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 获取当前积分
    const currentScoreValue = userStore.userInfo?.score || 0;
    // 计算新积分
    const newScore = currentScoreValue + 50;
    
    // 调用云函数更新积分
    const result = await uniCloud.callFunction({
      name: 'updateUserInfo',
      data: {
        body: JSON.stringify({
          action: 'updateUser',
          account: userStore.userInfo.account,
          score: newScore  // 直接在根级别传递score字段
        })
      }
    });

    if (result.result && result.result.status === 1) {
      // 打卡成功，标记为已打卡
      const today = new Date().toDateString();
      uni.setStorageSync('lastCheckinDate', today);
      
      // 更新打卡历史记录
      const checkinHistory = uni.getStorageSync('checkinHistory') || {};
      const yearMonth = `${currentYear.value}-${now.getMonth()+1}`;
      
      if (!checkinHistory[yearMonth]) {
        checkinHistory[yearMonth] = [];
      }
      
      checkinHistory[yearMonth].push(currentDay.value);
      uni.setStorageSync('checkinHistory', checkinHistory);
      
      // 更新状态
      isCheckedIn.value = true;
      checkinDays.value++;
      
      // 更新本地用户信息
      userStore.updateUserInfo({
        ...userStore.userInfo,
        score: newScore
      });
      
      // 更新当前显示积分
      currentScore.value = newScore;
      
      // 动画效果
      uni.showToast({
        title: '打卡成功，+50积分！',
        icon: 'success'
      });
      
      // 更新日历显示
      checkedDates.value.push(currentDay.value);
      // 重新计算日历数据
      updateCalendarDays();
      
    } else {
      uni.showToast({
        title: result.result?.message || '打卡失败，请稍后重试',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('打卡出错:', error);
    uni.showToast({
      title: '打卡失败，请稍后重试',
      icon: 'none'
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

onMounted(() => {
  checkUserCheckinStatus();
  getMonthlyCheckins();
  
  // 获取当前积分
  currentScore.value = userStore.userInfo?.score || 0;
  
  // 初始化日历数据
  updateCalendarDays();
});
</script>

<style lang="scss" scoped>
.checkin-page {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 40rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    
    .bi {
      font-size: 40rpx;
      color: #333;
    }
  }
  
  .title {
    font-size: 34rpx;
    font-weight: bold;
    color: #333;
  }
  
  .placeholder {
    width: 60rpx;
  }
}

.calendar-card {
  margin: 30rpx;
  background: linear-gradient(135deg, #6c8380 0%, #435553 100%);
  border-radius: 20rpx;
  padding: 30rpx;
  color: #fff;
  box-shadow: 0 10rpx 30rpx rgba(108, 131, 128, 0.3);
  position: relative;
  overflow: hidden;
  
  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url("https://epoch.jxksd.top/mo/images/ib0.jpg") no-repeat center center;
    background-size: cover;
    opacity: 0.15;
    z-index: 0;
  }
  
  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    position: relative;
    z-index: 1;
    
    .month {
      font-size: 40rpx;
      font-weight: bold;
    }
    
    .year {
      font-size: 32rpx;
      opacity: 0.8;
    }
  }
  
  .day-container {
    display: flex;
    align-items: baseline;
    position: relative;
    z-index: 1;
    
    .day {
      font-size: 120rpx;
      font-weight: bold;
      line-height: 1;
      margin-right: 20rpx;
    }
    
    .weekday {
      font-size: 36rpx;
      opacity: 0.9;
    }
  }
  
  .calendar-footer {
    margin-top: 20rpx;
    position: relative;
    z-index: 1;
    
    .lunar-date {
      font-size: 28rpx;
      opacity: 0.8;
    }
  }
}

.checkin-info {
  margin: 30rpx;
  display: flex;
  justify-content: space-between;
  
  .info-item {
    background: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
    width: 30%;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    
    .info-icon {
      font-size: 48rpx;
      color: #6c8380;
      margin-bottom: 10rpx;
    }
    
    .info-content {
      text-align: center;
      
      .info-title {
        font-size: 24rpx;
        color: #666;
        display: block;
        margin-bottom: 6rpx;
      }
      
      .info-value {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
    }
  }
}

.checkin-btn-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 40rpx 30rpx;
  
  .checkin-btn {
    width: 400rpx;
    height: 400rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #e7746c 0%, #d23c30 100%);
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 40rpx;
    font-weight: bold;
    box-shadow: 0 10rpx 30rpx rgba(210, 60, 48, 0.4);
    position: relative;
    transition: all 0.3s ease;
    
    &.checked {
      background: linear-gradient(135deg, #8da9a6 0%, #6c8380 100%);
      box-shadow: 0 10rpx 30rpx rgba(108, 131, 128, 0.4);
    }
    
    .checked-mark {
      position: absolute;
      top: 120rpx;
      left: 50%;
      transform: translateX(-50%);
      
      .bi {
        font-size: 60rpx;
      }
    }
    
    &:active {
      transform: scale(0.98);
    }
  }
  
  .checkin-tip {
    margin-top: 30rpx;
    font-size: 26rpx;
    color: #999;
    text-align: center;
  }
}

.mini-calendar {
  margin: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .calendar-title {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    padding-bottom: 16rpx;
    border-bottom: 2rpx solid #f0f0f0;
    
    .bi {
      font-size: 36rpx;
      color: #6c8380;
      margin-right: 10rpx;
    }
    
    text {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .week-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10rpx;
    
    .week-item {
      width: 14.28%;
      text-align: center;
      font-size: 24rpx;
      color: #999;
      padding: 10rpx 0;
    }
  }
  
  .days-grid {
    display: flex;
    flex-wrap: wrap;
    
    .day-item {
      width: 14.28%;
      height: 80rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      position: relative;
      
      text {
        font-size: 26rpx;
        color: #333;
      }
      
      &.other-month {
        text {
          color: #ccc;
        }
      }
      
      &.today {
        background: rgba(108, 131, 128, 0.1);
        border-radius: 8rpx;
        
        text {
          color: #6c8380;
          font-weight: bold;
        }
      }
      
      &.checked {
        .checked-dot {
          width: 10rpx;
          height: 10rpx;
          background: #e7746c;
          border-radius: 50%;
          position: absolute;
          bottom: 8rpx;
        }
      }
    }
  }
}
</style> 